﻿using System;
using System.Collections.Generic;
using System.Linq;
using GP.Scripts.City;
using Gp.Scripts.Core;
using PixelCrushers.DialogueSystem;
using QFramework;


namespace Gp.Scripts.Core {
    public class ConversationInfos {
        public string Character { get; set; } = "";

        public string Quest { get; set; } = "";

        public int QuestEntry { get; set; } = -1;

        public string ConversationTitle { get; set; }

        public int Priority { get; set; } = 2;
        
        
        public bool IsTrigger { get; set; }
        public bool IsActivator { get; set; }
        
        public bool IsOnce { get; set; }
        
        /// <summary>
        /// 是否是场景对话
        /// </summary>
        public bool IsScene { get; set; }
        
        
        
        
        
        public ConversationInfos(string conversationTitle) {
            ConversationTitle = conversationTitle;
        }


        public bool HasCharacter => !Character.IsNullOrEmpty();
        public bool HasQuest => !Quest.IsNullOrEmpty();
        public bool HasQuestEntry => QuestEntry != -1;
    }
    
    
    
    
    
    public class DialogueModel : BaseSystemData {
        private readonly Dictionary<string, List<ConversationInfos>> _dictionary = new();
        private HashSet<string> _characterSet;
        private HashSet<string> _questSet;
        private Dictionary<string, int> _conversationStats;

        // protected override void OnInit() {
            // var database = DialogueManager.instance.databaseManager.MasterDatabase;
            //
            // _characterSet = new HashSet<string>(database.actors.Select(x => x.Name));
            // _questSet = new HashSet<string>(database.items.Where(item => !item.IsItem).Select(x => x.Name));
            //
            // foreach (var info in
            //          database.conversations.Select(item => ResolveConversation(item.Title))) {
            //     var list = _dictionary.GetValueOrDefault(info.Character, new List<ConversationInfos>());
            //     list.Add(info);
            //     _dictionary[info.Character] = list;
            // }
        // }


        public ConversationInfos ResolveConversation(string conversationTitle) {
            ConversationInfos res = new(conversationTitle);
            if (conversationTitle.IsNullOrEmpty()) return res;

            var arr = conversationTitle.Split('/');
            foreach (var x in arr) {
                if (x.Length < 1) continue;
                // 仅处理指令 指令为包含$的字符串
                 if (x[0] != '$') continue;
                var word = x.Substring(1, x.Length - 1);

                
                
                // 判断保留字 是保留字则处理下一段对话
                if (KeyWordResolve(word)) continue;
                
                


                // 当x为角色或任务名称
                if (_questSet.Contains(word) && !res.HasQuest) {
                    res.Quest = word;
                }
                
                // 如果是场景对话
                if (word.Equals("scene")) {
                    res.IsScene = true;
                }
                
                // 角色名称
                else if (_characterSet.Contains(word) && !res.HasCharacter) {
                    res.Character = word;
                }

                // 当目标既非角色或任务名称，并且已经解析过其父任务，将其解析为entry
                // entry 格式： E1
                else if (res.HasQuestEntry && res.HasQuest && word.Length > 2 && word[0] == 'E') {
                    // res.QuestEntry = value;
                }
            }


            return res;
            
            
            
            
            bool KeyWordResolve(string word) {
                switch (word) {
                    case "trg" :
                        res.IsTrigger = true;
                        break;
                    case "atv" :
                        res.IsTrigger = true;
                        break;
                    case "once":
                        res.IsOnce = true;
                        break;
                    default :
                        return false;
                }

                return true;
            }
        }

        protected override void OnSave(SaveFile file)
        {
            throw new NotImplementedException();
        }

        protected override void OnLoad(SaveFile file)
        {
            throw new NotImplementedException();
        }

        protected override void OnClear()
        {
            throw new NotImplementedException();
        }


        // public override ISerializedModel OnSave() {
        //     return new SerializedDialogueModel(PersistentDataManager.GetSaveData());
        // }
        //
        // protected override void OnLoad(SerializedDialogueModel data) {
        //     PersistentDataManager.ApplySaveData(data.serializedData);
        // }


        public IEnumerable<ConversationInfos> GetConversationInfoList(string name) {
            return _dictionary.TryGetValue(name, out var res) ? res : Array.Empty<ConversationInfos>();
        }



        /// <summary>
        ///  获取对话（全局）的触发次数
        /// </summary>
        /// <returns></returns>
        public int ConversationCount(string name) {
            return _conversationStats.GetValueOrDefault(name, 0);
        } 

        
        public void OnConversationStarted(string target) {
        }


        public void OnConversationEnded(string target) {
            // _conversationStats[target]++;
            
            // 处理任务激活
            var info = ResolveConversation(target);
            
            
            if (info.IsActivator && info.HasQuest && QuestLog.IsQuestUnassigned(info.Quest)) {
                QuestLog.SetQuestState(info.Quest, QuestState.Active);
            }
        }


        public bool HasCharacter(string characterName) {
            return _characterSet.Contains(characterName);
        }
        
        
    }
}